import * as cc from 'cc';
import * as ecs from '@esengine/ecs-framework';
import { PREVIEW } from 'cc/env';
import { CocosRenderSystem } from './system/CocosRenderSystem';

const { ccclass, property, executionOrder } = cc._decorator;

@ccclass('ESCWorld')
@executionOrder(-100)
export class ESCWorld extends cc.Component {
    private scene: ecs.Scene;
    private entityManager: ecs.EntityManager;
    private static _instance: ESCWorld = null;

    static get instance() {
        return ESCWorld._instance;
    }

    protected __preload(): void {
        ESCWorld._instance = this;

        // 是否启用调试模式
        ecs.Core.create(true);

        this.scene = new ecs.Scene();
        this.scene.name = 'scene world';
        ecs.Core.setScene(this.scene);
        this.entityManager = new ecs.EntityManager();
    }

    onLoad() {
        //设置为常驻节点
        cc.director.addPersistRootNode(this.node);
    }

    start() {
        this.setupSystem();
    }

    update(dt) {
        ecs.Core.update(dt);
    }

    protected onDestroy(): void {
        this.scene.destroyAllEntities();
    }

    getScene() {
        return this.scene;
    }

    getEntityManager() {
        return this.entityManager;
    }

    private setupSystem() {
        this.scene.addEntityProcessor(new CocosRenderSystem(this.node));
    }
}
